package com.cloud.common.resolver;

import com.cloud.common.annotation.LoginUser;
import com.cloud.common.enums.LoginUserEnum;
import com.cloud.common.pojo.TokenUser;
import com.cloud.common.utils.JsonUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.List;

/**
 * @author zhozixiong
 * @date 2023/03/04
 */
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if(!parameter.hasParameterAnnotation(LoginUser.class)) {
            return false;
        }
        LoginUser loginUser = parameter.getParameterAnnotation(LoginUser.class);
        Class type = parameter.getParameterType();
        if (loginUser.value() == LoginUserEnum.UID && type.isAssignableFrom(String.class)) {
            return true;
        }else if(loginUser.value() == LoginUserEnum.ROLE && type.isAssignableFrom(String.class)) {
            return true;
        }else if (loginUser.value() == LoginUserEnum.AUTHORITY && type.isAssignableFrom(List.class)) {
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String json = URLDecoder.decode(request.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS), "utf-8");
        TokenUser tokenUser = JsonUtil.toBean(json, TokenUser.class);
        LoginUser loginUser = methodParameter.getParameterAnnotation(LoginUser.class);
        if(loginUser.value() == LoginUserEnum.UID) {
            return tokenUser.getUid();
        }else if(loginUser.value() == LoginUserEnum.ROLE) {
            return tokenUser.getRole();
        }else {
            return tokenUser.getAuthority();
        }
    }
}
